import React, { createContext } from 'react';
import { FormComponentProps } from 'antd/es/form';
import { connect, DispatchProp } from 'dva';
import { StoreState } from '@/common/store/store';
import AddBrandPanel from './components/AddPanel';
import FormModal from './components/FormModal';
import BrandListTable, { CategoryTableProps } from './components/CategoryListTable';

interface BrandListProps extends CategoryTableProps, DispatchProp {
  loading?: boolean;
}

interface BrandListState {
  showModal: boolean;
}

export const BrandTableContext = createContext<CategoryList>({} as CategoryList);

class CategoryList extends React.Component<BrandListProps, BrandListState> {
  formRef!: React.Component<FormComponentProps>;

  state: BrandListState = {
    showModal: false,
  };

  saveFormRef = (formRef: any) => {
    this.formRef = formRef;
  };

  handleSearch = () => {
    const { form } = this.formRef.props;
    const { dispatch } = this.props;
    dispatch({
      type: 'brand/query',
      payload: form.getFieldsValue(),
    });
  };

  onRowEdit = (id: number) => {
    console.log(id);
  };

  onRowDelete = (id: number) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'productAttributeCategory/remove',
      payload: id,
    });
  };

  showModal = () => {
    this.setState({ showModal: true });
  };

  handleCancel = () => {
    this.setState({ showModal: false });
  };

  handleCreate = () => {
    const that = this;
    const { form } = this.formRef.props;
    const { dispatch } = this.props;
    form.validateFields((err, values) => {
      if (!err && dispatch) {
        dispatch({
          type: 'productAttributeCategory/add',
          payload: values,
          callback: () => {
            form.resetFields();
            that.setState({ showModal: false });
          },
        });
      }
    });
  };

  render() {
    const { loading } = this.props;

    return (
      <div className="row-group">
        <AddBrandPanel onAddButtonClick={this.showModal} />
        <FormModal
          wrappedComponentRef={this.saveFormRef}
          visible={this.state.showModal}
          onCancel={this.handleCancel}
          onCreate={this.handleCreate}
          loading={this.props.loading}
        />
        <BrandTableContext.Provider value={this}>
          <BrandListTable categories={this.props.categories} loading={loading} />
        </BrandTableContext.Provider>
      </div>
    );
  }
}

const mapStateToProps = (state: StoreState) => ({
  categories: state.productAttributeCategory.categories,
  loading: state.loading.models.productAttributeCategory,
});

export default connect(mapStateToProps)(CategoryList);
